package com.sd.repay.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.sd.repay.cache.SysConfig;
import com.sd.repay.common.CommonResult;
import com.sd.repay.utils.Md5Util;
import com.sd.repay.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户端接口签名校验
 */
public class ClientSignValidateInterceptor extends HandlerInterceptorAdapter {
    private static Logger log = LoggerFactory.getLogger(ClientSignValidateInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> map = request.getParameterMap();
            for (Map.Entry<String, String[]> e : map.entrySet()) {
                String[] value = e.getValue();
                if (value != null && value.length == 1) {
                    params.put(e.getKey(), value[0]);
                } else {
                    params.put(e.getKey(), null);
                }
            }
            String fullContentType = "application/json;charset=UTF8";
            response.setCharacterEncoding("UTF-8");
            response.setContentType(fullContentType);

            String sign = request.getParameter("sign");
            if (StringUtil.isBlank(sign)) {
                response.getWriter().print(JSONObject.toJSONString(CommonResult.build(403, "签名参数不能为空")));
                return false;
            }

            String key = SysConfig.value("CLIENT_SIGN_KEY");
            String signSrc = StringUtil.buildSignSrc(false, params, "sign");
            signSrc += "&key=" + key;
            log.info("---->签名源串：" + signSrc);

            String signMsg = Md5Util.MD5Encode(signSrc, "UTF-8", false);
            if (!sign.equalsIgnoreCase(signMsg)) {
                response.getWriter().print(JSONObject.toJSONString(CommonResult.build(403, "签名验证失败")));
                return false;
            }
        }
        return true;
    }
}
